package com.cjc.sport.serviceimpl;

import com.cjc.sport.entity.Category;
import com.cjc.sport.entity.Course;
import com.cjc.sport.exception.ServiceException;
import com.cjc.sport.mapper.CategoryMapper;
import com.cjc.sport.mapper.CourseMapper;
import com.cjc.sport.service.CategoryService;
import com.cjc.sport.util.SportUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 课程分类表服务层实现类
 */
@Service(value = "categorySevice")
public class CategoryServiceImpl implements CategoryService {
    /**
     * @categoryMapper 装配课程分类mapper
     */
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * @courseMapper 装配课程mapper
     */
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public void addCategory(Category category) {
        // 查询课程分类是否有重名
        if (judgeDuplication(category)) {
            throw new ServiceException("已有此课程分类！");
        }
        // 设置uuid
        category.setCategoryId(SportUtils.getUuid());
        // 执行新增
        int i = categoryMapper.insertSelective(category);
        if (i != 1) {
            throw new ServiceException("新增失败!");
        }
        return;
    }

    @Override
    public void updateCategory(Category category) {
        // 查询重复课程分类
        if (judgeDuplication(category)) {
//            throw new ServiceException("已有此课程分类！");
        }
        // 执行编辑
        int i = categoryMapper.updateByPrimaryKeySelective(category);
        if (i != 1) {
            throw new ServiceException("编辑失败!");
        }
        // 编辑相关课程
        Course course = new Course();
        course.addCategoryId(category.getCategoryId())
                .addCategoryName(category.getCategoryName());
        courseMapper.updateByCategoryId(course);
        return;
    }

    @Override
    public void deleteCategory(Category category) {
        // 查询相关课程
        List<Course> courses = courseMapper.selectByCategoryId(category);
        if (!courses.isEmpty()) {
            throw new ServiceException("无法进行此操作，请确认该课程分类下无相关课程！");
        }
        // 执行删除
        int i = categoryMapper.deleteByPrimaryKey(category.getCategoryId());
        if (i != 1) {
            throw new ServiceException("删除失败!");
        }
        return;
    }

    @Override
    public List<Category> getAllCategories() {
        // 执行查询
        List<Category> categories = categoryMapper.selectAllCategory();
        if (categories.isEmpty()) {
            throw new ServiceException("暂无相关记录!");
        }
        return categories;
    }

    /**
     * 判断数据库中是否有重名课程分类
     *
     * @param category 课程分类对象
     * @return true 有 false 无
     */
    public boolean judgeDuplication(Category category) {
        List<Category> categories = categoryMapper.selectCategoryName(category.getCategoryName());
        if (!categories.isEmpty()) {
            return true;
        }
        return false;
    }
}
